package com.hn658.base.message.notisender.sender.comet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.hn658.base.message.common.utils.RedisKeyHelper;
import com.hn658.base.message.notisender.message.CometMessage;
import com.hn658.framework.dataaccess.redis.AbstractRedisDAO;

@Component
public class IsOnlineManagerImpl extends AbstractRedisDAO<CometMessage> implements IIsOnlineManager {

	@Autowired
	@Qualifier("redisTemplate")
	@Override
	public void setTemplate(StringRedisTemplate template) {
		super.template = template;
	}
	
	@Override
	public void offline(String appKey, String userId) {
		this.setOnlineStatus(appKey, userId, false);
		//清楚当前用户聊天对象缓存
		template.delete(RedisKeyHelper.talkerKeyById(appKey, userId));
	}

	@Override
	public void online(String appKey, String userId) {
		this.setOnlineStatus(appKey, userId, true);
	}
	
	public void setOnlineStatus(String appKey, String userId, boolean isOnline){
		if (appKey == null) {
            return;
        }
        BoundHashOperations<String, String, String> userOps = template
                .boundHashOps(RedisKeyHelper.accountInfo(appKey, userId));

        if (isOnline) {
        	userOps.put(RedisKeyHelper.lastActiveDateTime(),
                    String.valueOf(System.currentTimeMillis()));
        } else {
        	userOps.put(RedisKeyHelper.lastActiveDateTime(), "0");
        }
	}

    @Override
    public boolean isonline(String appKey, String userId){
        boolean isonline = true;
        BoundHashOperations<String, String, String> userOps = template
                .boundHashOps(RedisKeyHelper.accountInfo(appKey, userId));
        String lastActiveDateTime = userOps.get(RedisKeyHelper.lastActiveDateTime());
        if(StringUtils.isEmpty(lastActiveDateTime)||"0".equals(lastActiveDateTime)){
            isonline = false;
        }
        return isonline;

    }

}
